/**
 * 
 */
package de.idgard.android.addon.services.transport;

import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;

import org.apache.http.conn.ssl.SSLSocketFactory;

import android.content.Context;
import de.idgard.android.R;

/**
 * 
 * @author <a href="mailto:vesko.georgiev@uniscon.com">Vesko Georgiev</a>
 */
public class IDGCertificateManager {

	private static final String PASS = "nababatihvarchiloto";

	private KeyStore keyStore;
	private Context context;

	public IDGCertificateManager(Context context) {
		this.context = context;
		keyStore = getCertificate();
	}

	/**
	 * @return the pass
	 */
	public String getPass() {
		return PASS;
	}

	/**
	 * @return the keyStore
	 */
	public KeyStore getKeyStore() {
		return keyStore;
	}

	public SSLSocketFactory newSslSocketFactory() throws Exception {
		return new SSLSocketFactory(this.keyStore, PASS, keyStore);
	}

	public KeyStore getCertificate() {
		InputStream in = null;
		try {
			KeyStore trusted = KeyStore.getInstance("BKS");
			in = context.getResources().openRawResource(R.raw.idgard_key_store);
			trusted.load(in, PASS.toCharArray());
			return trusted;
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			if (in != null) {
				try {
					in.close();
				}
				catch (IOException e) {
					//
				}
			}
		}
		return null;
	}
}
